class Hour < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user_id
  before_save :check_if_day_has_changed

  def self.populate_data(xml)
    counter = { :users => 0, :days => 0, :hours => 0 }
    doc = REXML::Document.new(xml)
    doc.elements.each('data/user') do |u|
      counter[:users] += 1
      prev = nil
      u.elements.each('day') do |d|
        counter[:days] += 1
        d.elements.each('hour') do |h|
          counter[:hours] += 1
          date = DateTime.strptime(d.attribute("date").value+" "+h.attribute("time").value, "%d/%m/%Y %H:%M")
          r = Hour.new :user_id => User.find_by_login(u.attribute("login").value).id, 
                       :notes => I18n.t(:migrated_auto),
                       :ip => h.attribute("ip").value,
                       :in_or_out => h.attribute("in_or_out").value,
                       :created_at => date 
          if prev.present? and prev.in_or_out == 'in' and prev.created_at.utc.tomorrow.strftime("%d/%m/%Y") == date.utc.strftime("%d/%m/%Y")
            close = Hour.new :ip => prev.ip, :user_id => prev.user_id, :in_or_out => 'out', :created_at => date.utc.yesterday.end_of_day
            close.send :create_without_callbacks
            open = Hour.new :ip => prev.ip, :user_id => prev.user_id, :in_or_out => 'in', :created_at => date.utc.beginning_of_day
            open.send :create_without_callbacks
          end
          r.send :create_without_callbacks
          prev = r.reload
        end
      end
    end
    counter
  end

  private

  def check_if_day_has_changed
    last = self.user.punches.first :order => "created_at DESC" if self.user.is_a?(User) and self.user.ever_worked?
    
    if last.present? and last.in_or_out == 'in' and last.created_at.utc.tomorrow.strftime("%d/%m/%Y") == Time.now.utc.strftime("%d/%m/%Y")
        
       close = Hour.new :ip => ip, :user_id => user_id, :in_or_out => 'out', :created_at => Time.now.utc.yesterday.end_of_day
       close.send :create_without_callbacks
 
       open = Hour.new :ip => ip, :user_id => user_id, :in_or_out => 'in', :created_at => Time.now.utc.beginning_of_day
       open.send :create_without_callbacks

    end
  end

end
